$.fn.treegrid = function (opt,params) {
    var tree = $(this);
    if( opt == 'reload' ){
        var options = tree.data();
        options.queryParams = params;
        loadTree(options,tree);
        return;
    }else if( opt == 'loadData' ){
        var options = tree.data();
        var treeData = transTreeData(params,options.root);
        if( params.length > 0 && treeData.length == 0 ){
            treeData = params;
        }
        var levelIndex = 1;
        loadTreeData(options,treeData,tree,levelIndex);
    }

    var options = {root:-1,head:true};
    $.extend(options,opt);
    tree.addClass("vui-table");
    tree.data(options);
    if(options.width){
        tree.width(options.width);
        tree.css({"margin":"0px"});
    }

    loadTree(options,tree);
};


function loadTree(options,tree) {
    loadTreeUrl(options,function (response) {
        if(options.rootData){
            response.data.push(options.rootData);
        }
        var treeData = transTreeData(response.data,options.root);
        if( response.data.length > 0 && treeData.length == 0 ){
            treeData = response.data;
        }
        var levelIndex = 1;

        loadTreeData(options,treeData,tree,levelIndex);
    });
}

function loadTreeData(options,rows,tree,levelIndex){
    tree.empty();
    for( var i=0 ; i<rows.length ; i++ ){
        //this is load root,other is load children
        loadTreeRow(options,rows[i],tree,levelIndex);
    }
    if( options.check ){
        tree.find('input[type=checkbox]').click(function () {
            treeNodeCheck(tree,$(this));
        });
    }
    if(options.loadSuccess){options.loadSuccess()};
}

function treeNodeCheck(tree,that) {
    var checked = that.prop('checked'),tid = that.parent().attr('tid');
    tree.find('.vui-tree-icons[pid='+tid+'] input[type=checkbox]').prop('checked',checked);
    tree.find('.vui-tree-icons[pid='+tid+'] .fa-folder').parent().find('input[type=checkbox]').each(function () {
        treeNodeCheck(tree,$(this));
    });
}

function loadTreeRow(options,rowData,tree,index){
    var row = $('<div pid="'+rowData.parentId+'" tid="'+rowData.id+'" class="vui-table-row" type="body"></div>');
    row.data(rowData);

    for(var i=0 ; i<options.columns.length ; i++){
        var column = options.columns[i];
        var cell = $('<div class="vui-table-cell"></div>');
        if( i==0 ){
            var icons = $('<span pid="'+rowData.parentId+'" tid="'+rowData.id+'" class="vui-tree-icons" style="margin-left: '+(15*index)+'px;">');

            if( rowData.isLeaf == 0 ){
                // has children
                icons.append('<i dis="show" class="fa fa-caret-right vui-tree-expand"></i>');
                if(options.check)icons.append('<input type="checkbox" value="'+rowData.id+'" class="ck-fo"/>');

                if(options.check){
                    icons.append('<i class="fa fa-folder"></i>');
                }else{
                    icons.append('<i class="fa fa-folder  file-nock"></i>');
                }

            }else{
                if(options.check)icons.append('<input type="checkbox" value="'+rowData.id+'" class="ck-fi" />');
                if(options.check){
                    icons.append('<i class="fa fa-file"></i>');
                }else{
                    icons.append('<i class="fa fa-file  file-nock"></i>');
                }

            }

            if(options.check){
                icons.append('<span class="txt">'+getTreeCellValue(rowData,column)+'</span>');
            }else{
                icons.append('<span class="txt txt-nock">'+getTreeCellValue(rowData,column)+'</span>');
            }

            cell.addClass('vui-tree-cell');
            cell.append(icons);
        }else{
            cell.append(getTreeCellValue(rowData,column));
        }
        row.append(cell);
    }

    tree.append(row);
    if( options.click ){
        row.click(function () {
            options.click(rowData);
        });
    }
    loadChildrenRows(options,rowData,tree,index);

}

function loadChildrenRows(options,rowData,tree,index){
    if( !rowData || !rowData.children || rowData.children.length ==0 ){
        return;
    }
    for( var k =0 ; k<rowData.children.length ; k++ ){
        loadTreeRow(options,rowData.children[k],tree,index+1);
    }
}

function getTreeCellValue(rowData,column) {
    var value;
    if( column.formatter ){
        value = column.formatter(rowData);
    }else{
        value = rowData[column.field];
    }
    if( value == null || value == undefined )value = '';
    return value;
}

function hideChildren( srow,dis ) {
    $('.vui-table-row[p="'+srow.attr('tid')+'"]').each(function(){
        if( dis == 'show' ){
            $(this).hide();
        }else{
            $(this).show();
        }

        hideChildren($(this),dis);
    });
}

function loadTreeUrl(options,callback) {
    var data =$.extend(options.queryParams,{loginUserId:top.loginUserId,customerId:top.customerId,loginCompanyId:top.loginCompanyId,loginCompanyLogicalCode:top.loginCompanyLogicalCode});
    
    $.ajax({
        url:options.url,
        data:data,
        dataType:'json',
        success:callback
    });
}

function transTreeData(rows,parentId){
    var treeData = [];
    for( var i=0 ; i<rows.length ; i++ ){
        var row = rows[i];
        if( row.parentId == parentId ){
            var children = transTreeData(rows,row.id);
            if(children && children.length>0){
                row.children = children;
                row.isLeaf = 0;
            }else{
                row.isLeaf = 1;
            }
            treeData.push(row);
        }
    }
    return treeData;
}